﻿using Foundation.Service.Bus.Core;
using Microsoft.Extensions.DependencyInjection;
using Dyao.Book.Application.Abstractions;
using Dyao.Book.BusContract;
using Foundation.DistributeLock;
using Microsoft.Extensions.Logging;
using Foundation.Core;

namespace Dyao.Book.BusApplication
{
    public class SpiderLongRunningBusService : BaseBusService
    {
        public async Task Handle_TestCommandAsync(MessageHandleContext<TestCommand> handleContext)
        {
            await handleContext.LoggingAsync("Handle_TestCommandAsync", "test", async () =>
            {
                var cancellationToken = handleContext.GetCancellationToken();
                await Task.CompletedTask;
            });
        }

        /// <summary>
        /// 爬取起点书籍信息
        /// </summary>
        /// <param name="handleContext"></param>
        /// <returns></returns>
        public async Task Handle_QiDianSpiderCommandAsync(MessageHandleContext<QiDianBookSpiderCommand> handleContext)
        {
            await handleContext.LoggingAsync("Handle_QiDianSpiderCommandAsync", "QiDianBookSpider", async () =>
            {
                var cancellationToken = handleContext.GetCancellationToken();
                var qidianSpider = handleContext.ServiceProvider.GetRequiredService<IQiDianBookSpider>();
                await qidianSpider.GetBooksByPageAsync(handleContext.Message.Page, cancellationToken);
            });
        }

        /// <summary>
        /// 爬取章节目录
        /// </summary>
        /// <param name="handleContext"></param>
        /// <returns></returns>
        public async Task Handle_QiDianBookChaptersSpiderCommandAsync(MessageHandleContext<QiDianBookChaptersSpiderCommand> handleContext)
        {
            await handleContext.LoggingAsync("Handle_QiDianBookChaptersSpiderCommandAsync", "QiDianBookChaptersSpider", async () =>
            {
                var cancellationToken = handleContext.GetCancellationToken();
                var qidianSpider = handleContext.ServiceProvider.GetRequiredService<IQiDianBookCatalogueSpider>();
                var logger = handleContext.ServiceProvider.GetRequiredService<ILogger<SpiderLongRunningBusService>>();
                var redLock = handleContext.ServiceProvider.GetRequiredService<IDistributeLocker>();
                var locker = await redLock.CreateNonBlockingLockAsync($"BookChapters-{handleContext.Message.Craw.BookId}", TimeSpan.FromMinutes(5));

                await locker.UsingNonBlockingLockAsync(async () =>
                {
                    await qidianSpider.CrawCatalogueByBookAsync(handleContext.Message.Craw, cancellationToken);
                }, async () =>
                {
                    logger.LogInformation($"Handle_QiDianBookChaptersSpiderCommandAsync, 书籍编号：{handleContext.Message.Craw.BookId} 正在处理.");
                    await Task.CompletedTask;
                });
            });
        }

        /// <summary>
        /// 爬取正文
        /// </summary>
        /// <param name="handleContext"></param>
        /// <returns></returns>
        public async Task Handle_QiDianBookContentSpiderCommandAsync(MessageHandleContext<QiDianBookContentSpiderCommand> handleContext)
        {
            await handleContext.LoggingAsync("Handle_QiDianBookContentSpiderCommandAsync", "QiDianBookContentSpiderCommand", async () =>
            {
                var cancellationToken = handleContext.GetCancellationToken();
                var qidianSpider = handleContext.ServiceProvider.GetRequiredService<IQiDianBookCatalogueContentSpider>();
                var logger = handleContext.ServiceProvider.GetRequiredService<ILogger<SpiderLongRunningBusService>>();
                var redLock = handleContext.ServiceProvider.GetRequiredService<IDistributeLocker>();

                var locker = await redLock.CreateNonBlockingLockAsync($"BookContent-{handleContext.Message.BatchNo}", TimeSpan.FromMinutes(5));

                await locker.UsingNonBlockingLockAsync(async () =>
                {
                    await qidianSpider.CrawlContentByCataloguesAsync(handleContext.Message.Craws, cancellationToken);
                }, async () =>
                {
                    logger.LogInformation($"Handle_QiDianBookContentSpiderCommandAsync, 批次：{handleContext.Message.BatchNo} 正在处理.");
                    await Task.CompletedTask;
                });

            });
        }

        /// <summary>
        /// 爬虫日志
        /// </summary>
        /// <param name="handleContext">上下文</param>
        /// <returns></returns>
        public async Task Handle_SpiderLogCommandAsync(MessageHandleContext<SpiderLogCommand> handleContext)
        {
            await handleContext.LoggingAsync("Handle_SpiderLogCommandAsync", "SpiderLog", async () =>
            {
                var cancellationToken = handleContext.GetCancellationToken();
                var spider = handleContext.ServiceProvider.GetRequiredService<ISpiderApplication>();
                await spider.AddLogsAsync(handleContext.Message.Logs, cancellationToken);
            });
        }

        /// <summary>
        /// 同步书籍章节目录-任务中心
        /// </summary>
        /// <param name="handleContext">上下文</param>
        /// <returns></returns>
        public async Task Handle_SyncBookChapterTaskCenterCommandAsync(MessageHandleContext<SyncBookChapterTaskCenterCommand> handleContext)
        {
            await handleContext.LoggingAsync("Handle_SyncBookChapterTaskCenterCommandAsync", "同步书籍章节", async () =>
            {
                var can = handleContext.GetCancellationToken();
                var service = handleContext.ServiceProvider.GetService<IBookCatalogueApplication>();
                await service.SyncBookChapterAsync(handleContext.Message.TaskCenterDto, can);
            });
        }

        /// <summary>
        /// 同步书籍的相关书源
        /// </summary>
        /// <param name="handleContext">上下文</param>
        /// <returns></returns>
        public async Task Handle_SyncBookSourceCommandAsync(MessageHandleContext<SyncBookSourceCommand> handleContext)
        {
            await handleContext.LoggingAsync("Handle_SyncBookSourceCommandAsync", "同步书籍的相关书源", async () =>
            {
                var cancellationToken = handleContext.GetCancellationToken();
                var service = handleContext.ServiceProvider.GetService<IBookMgrApplication>();
                await service.SyncBookSourceAsync(handleContext.Message.TaskCenterDto, cancellationToken);
            });
        }

        /// <summary>
        /// 同步书籍章节目录
        /// </summary>
        /// <param name="handleContext">上下文</param>
        /// <returns></returns>
        public async Task Handle_SyncBookChapterCommandAsync(MessageHandleContext<SyncBookChapterCommand> handleContext)
        {
            await handleContext.LoggingAsync("Handle_SyncBookChapterCommandAsync", "同步书籍章节", async () =>
            {
                var can = handleContext.GetCancellationToken();
                var service = handleContext.ServiceProvider.GetService<IBookCatalogueApplication>();
                await service.SyncBookChapterAsync(handleContext.Message.Chapter, can);
            });
        }

        /// <summary>
        /// 爬取章节内容
        /// </summary>
        /// <param name="handleContext">上下文</param>
        /// <returns></returns>
        public async Task Handle_SyncCrawlContentCommandAsync(MessageHandleContext<SyncCrawlContentCommand> handleContext)
        {
            await handleContext.LoggingAsync("Handle_SyncCrawlContentCommandAsync", "爬取章节内容", async () =>
            {
                var cancellationToken = handleContext.GetCancellationToken();
                var service = handleContext.ServiceProvider.GetService<IBookContentApplication>();
                await service.CrawlContentAsync(handleContext.Message.TaskCenterDto, cancellationToken);
            });
        }

        /// <summary>
        /// 手动爬取章节内容
        /// </summary>
        /// <param name="handleContext">上下文</param>
        /// <returns></returns>
        public async Task Handle_SyncManualCrawlContentCommandAsync(MessageHandleContext<SyncManualCrawlContentCommand> handleContext)
        {
            await handleContext.LoggingAsync("Handle_SyncManualCrawlContentCommandAsync", "手动爬取章节内容", async () =>
            {
                var cancellationToken = handleContext.GetCancellationToken();
                var service = handleContext.ServiceProvider.GetService<IBookContentApplication>();
                await service.ManualCrawlContentAsync(handleContext.Message.TaskCenterDto, cancellationToken);
            });
        }

        /// <summary>
        /// 匹配章节源
        /// </summary>
        /// <param name="handleContext">上下文</param>
        /// <returns></returns>
        public async Task Handle_SyncBookChapterSourceCommandAsync(MessageHandleContext<SyncBookChapterSourceCommand> handleContext)
        {
            await handleContext.LoggingAsync("Handle_SyncBookChapterSourceCommandAsync", "匹配章节源", async () =>
            {
                var cancellationToken = handleContext.GetCancellationToken();
                var service = handleContext.ServiceProvider.GetService<IBookCatalogueApplication>();
                await service.MatchChapterSourceAsync(handleContext.Message.BookId, cancellationToken);
            });
        }
    }
}
